//
//  CommentInputView.swift
//  WeiboDemo
//
//  Created by 姬向阳 on 2020/4/28.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI

struct CommentInputView: View {
    // 添加评论的Post
    var post : Post
    // 用于绑定CommentTextView中的Text
    @State private var text : String = ""
    // 用于控制'评论不能为空'的显示与隐藏
    @State private var showEmptyTextHUD: Bool = false
    // 系统环境,presentationMode与模态推出页面有关
    @Environment(\.presentationMode) var presentationMode
    // 添加环境对象
    @EnvironmentObject var userData : UserData
    // 键盘事件监听对象
    @ObservedObject private var keyboardResponder = KeyboardResponder()
    
    var body: some View {
        VStack(spacing: 0) {
            CommentTextView(text: $text, beginEdittingOnAppear: true)
            HStack {
                Button(action: {
                    // 修改环境变量中的值,使模态推出页面消失
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("取消").padding()
                }
                Spacer()
                Button(action: {
                    if self.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty{
                        self.showEmptyTextHUD = true
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                            self.showEmptyTextHUD = false
                        }
                        return
                    }
                    print(self.text)
                    // 设置一个局部变量
                    var post = self.post
                    // 让局部变流量评论数+1
                    post.commentCount += 1
                    // 局部变量回传给环境变量
                    self.userData.update(post)
                    // 使模态推出页消失
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("发送").padding()
                }
            }
            .font(.system(size: 18))
            .foregroundColor(.black)
        }
        .overlay(
            Text("评论不能为空")
                .scaleEffect(showEmptyTextHUD ? 1 : 0.5)
                .animation(.spring(dampingFraction:0.5))
                .opacity(showEmptyTextHUD ? 1 : 0)
                .animation(.easeInOut)
        )
            // 使整个页面添加一个与屏幕底部的padding,高度为键盘高度
            .padding(.bottom,keyboardResponder.keyboardHeight)
            // 键盘显示时忽略底部安全区域,键盘消失时不忽略安全区域,使用空集[]来表示
            .edgesIgnoringSafeArea(keyboardResponder.keyboardShow ? .bottom : [])
    }
}

struct CommentInputView_Previews: PreviewProvider {
    static var previews: some View {
        CommentInputView(post: UserData().recommendPostList.list[0])
    }
}
